package com.travel.server.manager.impl.command.data;

import com.travel.common.excel.ExcelData;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.DateUtil;
import com.travel.common.util.ExcelUtil;
import com.travel.server.manager.dto.request.data.ExportTradeListRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.dto.response.data.QueryTradeListResponse.TradeItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/14 19:15
 * @Desc:
 */
@Component
@Slf4j
public class ExportTradeListCommand extends AbstractCommand<ExportTradeListRequest, EmptyResponse> {

    @Autowired
    private QueryTradeListCommand command;

    @Override
    protected void checkInput(ExportTradeListRequest request) {
        checkTimeInput(request);
    }

    @Override
    public EmptyResponse handle(ExportTradeListRequest request) {
        checkInput(request);
        Date startTime = DateUtil.getDataTime(request.getStartTime());
        Date endTime = DateUtil.getDataEndTime(request.getEndTime());
        List<TradeItem> list = command.makeList(startTime,endTime,null,null);
        if(CollectionUtil.isEmpty(list)){
            throw new WorkException(WorkCode.EXCEL_DATA_NULL);
        }
        List<String> title = Arrays.asList("用户名", "订单号", "订单名称", "订单金额", "支付状态", "下单时间", "交易流水号", "备注");
        List<List<Object>> rows = new ArrayList<>();
        String fileName = "交易记录";
        for(TradeItem item : list){
            List<Object> objects = new ArrayList<>();
            objects.add(item.getCustomerName());
            objects.add(item.getOrderId());
            objects.add(item.getOrderDesc());
            objects.add(item.getOrderAmount());
            objects.add(item.getPayStatus());
            if(item.getTradeDate() != null){
                objects.add(DateUtil.dateToStr(item.getTradeDate(), DateUtil.YYYY_MM_DD));
            }else{
                objects.add("");
            }
            objects.add(item.getTradeNum());
            objects.add(item.getRemark());
            rows.add(objects);
        }
        ExcelData excelData = new ExcelData(title, rows, fileName);
        ExcelUtil.exportExcel(getHttpServletResponse(), fileName, excelData);
        return new EmptyResponse();
    }
}
